/*
 * @Author: wwssaabb
 * @Date: 2021-12-16 09:55:36
 * @LastEditTime: 2021-12-16 10:16:05
 * @FilePath: \handwritten-code\main\数字化金额.js
 */

/* 
  数字化金额,例如 1,567,388
*/


//for循环
function numFormat(number, format = ',') {
  if (isNaN(number)) return TypeError('type Error')
  let strArr = String(number).split('').reverse(),
    res = []
  for (let i = 0; i < strArr.length; i++) {
    res.unshift(((i + 1) % 3 === 0 && i !== 0 && i !== strArr.length - 1) ? (format + strArr[i]) : strArr[i])
  }
  return res.join('')
}

//reduce
function numFormat(number, format = ',') {
  return String(number).split('').reverse().reduce((p, c, i, arr) => {
    p.unshift(((i + 1) % 3 === 0 && i !== 0 && i !== arr.length - 1) ? (format + c) : c);
    return p
  }, []).join('')
}

//正则替换
function numFormat(number, format = ',') {
  return String(number).replace(/\B(?=(\d{3})+$)/g, format)
}


console.log(numFormat(156738888))
console.log(numFormat(15673888))
console.log(numFormat(1567388))